package dabs.engine.plant;

import dabs.engine.control.ComponentCommand;
import dabs.engine.environment.AcceptsModifier;
import dabs.engine.environment.Modifier;
import dabs.engine.environment.TemporaryDisable;
import dabs.engine.messaging.Notification;
import dabs.engine.messaging.NotificationHandler;

public class Condenser extends Converter implements AcceptsModifier{
	private static final long serialVersionUID = -1755486795151965016L;

	public Condenser(NotificationHandler mailBox, String name, int conversionRate, int capacity, int outRate) {
		super(mailBox, name, conversionRate, capacity, outRate);
	}
	
	private int saveSpeed = 0;
	
	public int getCondensingSpeed() { return getConversionRate(); }
	
	public void setCondensingSpeed( int condensingSpeed ) { 
		if ( isDeactivated() == false ) {
			setConversionRate(condensingSpeed); 
			passMessage(new Notification(getName(), "Speed set to " + condensingSpeed + "%."));
		} else {
			passMessage( new Notification(getName(), "is stalled") );
		}
		
	}
		
	@Override
	protected void receiveModifier(Modifier modifier) {
		super.receiveModifier(modifier);
		if (modifier instanceof TemporaryDisable) {
			saveSpeed = getCondensingSpeed();
			setConversionRate(0); 
		} else { 
			throw new RuntimeException("wtf is this modifier? " + modifier.getClass().getName());
		}
	}
	
	@Override
	protected void inactivatedModifier(Modifier modifier) {
		super.inactivatedModifier(modifier);
		if (modifier instanceof TemporaryDisable) {
			passMessage(new Notification(getName(), "is now active again"));
			setConversionRate(saveSpeed);			
		}
	}
	public void convert() {
		getNewHydroState().convert(getConversionRate(), true);
	}
	
	@Override
	public void tick() {
		getNewHydroState().sendToNext(getHydroProp().getOutRate(), true, getOutputs(), getPressure());
		// Lose health if running at more than 80% capacity equal to percentage over 80%
		if (getCondensingSpeed() > 80) 
			setHealth(getHealth() - (getCondensingSpeed() - 80));
		super.tick();
	}
	
	@Override
	public void runCommand(ComponentCommand command) {
		assert(command.getDestination().equals(getName()));
		try{
			int newSpeed = Integer.parseInt(command.getArguments().get(0)); //Line to be changed depending on arguments.
			if (newSpeed <= 100 && newSpeed >= 0){
			setCondensingSpeed(newSpeed);
			}
			else{
			passMessage(new Notification(getName(), "Speed  must be set to a value between 0 and 100"));
			}
		}
		catch (java.lang.NumberFormatException e){
			passMessage(new Notification(getName(), "Speed must be set to an integer value."));
			return;
		}
	}
	
	@Override
	public String read() {
		return String.format("%s\tCondensing speed: %d%%\n", super.read(), getCondensingSpeed());
	}
}
